package http.core;

import action.DoAction;
import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import util.AESUtils;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import static com.sun.deploy.net.HttpRequest.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

/**
 * Created by zhangting on 02/04/2019.
 */
public class HttpDispatcher extends SimpleChannelInboundHandler<FullHttpRequest> {

    private final static DoAction action = new DoAction();

    @Override
    public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest) throws Exception {
        System.out.println("uri------");
        String uri = fullHttpRequest.uri();
        System.out.println(uri);
        JSONObject jsonRootObj = new JSONObject();
        String param = handleParam(ctx, fullHttpRequest);
        param = biz(uri, param);
        if ("".equals(param)) {
            jsonRootObj.put("result", "fail");
        } else {
            jsonRootObj.put("result", "ok");
            //jsonRootObj.put("data", param);
        }

        String responsecore = AESUtils.aesEncrypt(jsonRootObj.toJSONString(), action.getKey());

        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);
        response.headers().set(CONTENT_TYPE, "application/json; charset=UTF-8");
        ByteBuf buffer = Unpooled.copiedBuffer(responsecore, CharsetUtil.UTF_8);
        response.content().writeBytes(buffer);
        buffer.release();
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);

    }

    private String biz(String uri, String body) {

        if ("".equals(body)) {
            return "";
        }
        if (uri.startsWith("/yxapi/getBody")) {
            return action.getBody(body);
        } else if (uri.startsWith("/yxapi/seed")) {
            return action.getKey();
        }
        return "";
    }

    private static String handleParam(
            ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest)
            throws UnsupportedEncodingException {
        HttpHeaders headers = fullHttpRequest.headers();
        Map<String, Object> mapReturnData = new HashMap<String, Object>();
        if (headers.get("Content-Type") == null || headers.get("Content-Type").equals("")) {
            return "";
        }
        String strContentType = headers.get("Content-Type");

        if (fullHttpRequest.method() == HttpMethod.GET) {
            return "";
        } else if (fullHttpRequest.method() == HttpMethod.POST) {
            // 处理POST请求
            if (strContentType.contains("application/json")) {
                // 解析json数据
                ByteBuf content = fullHttpRequest.content();
                if (content.capacity() == 0) {
                    return "";
                }
                byte[] reqContent = new byte[content.readableBytes()];
                content.readBytes(reqContent);
                String strContent = new String(reqContent, "UTF-8");
                //System.out.println("接收到的消息" + strContent);
                return strContent;
            }
        }
        return "";
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        System.out.println(cause.getStackTrace());
        cause.printStackTrace();
        ctx.channel().close();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

}
